var dh = Ext.DomHelper;

function getRosters() {
    RosterService.getRosters(function (rosters) {
        var listElement = document.getElementById("rosters");
        updateList(listElement, rosters, selectRoster);
    });
}

function getPeople() {
    RosterService.getPeople(function (people) {
        var peopleList = document.getElementById("people");
        updateList(peopleList, people, makeDragable);
    });
}

function makeDragable(listElement, person) {
    new DragableElement(function() {
        var roster = rosterDetailsController.getRoster();
        RosterService.addPersonToRoster(person.id, roster.id, rosterDetailsController.displayPeople);
    }, listElement, rosterDetailsController.getDragableGroup());
}

function selectRoster(listElement, domainObject) {
    listElement.onclick = function() {
        rosterDetailsController.loadRoster(domainObject);
    };
}

function deleteChildren(element) {
    while (element.hasChildNodes()) {
        element.removeChild(element.firstChild);
    }
}

function updateList(listElement, domainObjects, applyFunction) {
    deleteChildren(listElement);
    for (var i = 0; i < domainObjects.length; i++) {
        var li = document.createElement("li");
        var domainObject = domainObjects[i];
        li.innerHTML = domainObject.name;
        listElement.appendChild(li);
        applyFunction(li, domainObject);
    }
}


function createDomainObjectCreator(title, createFunction, updateFunction) {
    var entryDiv = document.createElement("div");
    entryDiv.className = "Entry";
    var span = document.createElement("span");
    span.innerHTML = title;
    var inputDiv = document.createElement("div");
    var text = document.createElement("input");
    var button = new YAHOO.widget.Button(
    {
        type: "push",
        label: "create"
    });
    button.addListener("click", function() {
        createFunction(text.value, updateFunction);
    });

    entryDiv.appendChild(span);
    entryDiv.appendChild(inputDiv);
    inputDiv.appendChild(text);
    button.appendTo(inputDiv);

    document.body.appendChild(entryDiv);

}